

import React, { useState, useEffect } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import styles from './styles.module.css';

const HomePage: React.FC = () => {
  const navigate = useNavigate();
  const [showNotificationDropdown, setShowNotificationDropdown] = useState(false);
  const [showUserDropdown, setShowUserDropdown] = useState(false);
  const [searchInputValue, setSearchInputValue] = useState('');

  useEffect(() => {
    const originalTitle = document.title;
    document.title = '食算 - 首页';
    return () => { document.title = originalTitle; };
  }, []);

  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      const target = event.target as Element;
      
      const notificationContainer = document.querySelector('#notification-container');
      const userMenuContainer = document.querySelector('#user-menu-container');
      
      if (notificationContainer && !notificationContainer.contains(target)) {
        setShowNotificationDropdown(false);
      }
      
      if (userMenuContainer && !userMenuContainer.contains(target)) {
        setShowUserDropdown(false);
      }
    };

    document.addEventListener('click', handleClickOutside);
    return () => {
      document.removeEventListener('click', handleClickOutside);
    };
  }, []);

  const handleQuickAddClick = () => {
    navigate('/food-search');
  };

  const handleQuickSearchClick = () => {
    navigate('/food-search');
  };

  const handleQuickCameraClick = () => {
    navigate('/food-search');
  };

  const handleQuickLibraryClick = () => {
    navigate('/food-search');
  };

  const handleRecordItemClick = () => {
    navigate('/record-list');
  };

  const handleViewAllRecordsClick = (e: React.MouseEvent) => {
    e.preventDefault();
    navigate('/record-list');
  };

  const handleSearchKeyPress = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      navigate('/food-search');
    }
  };

  const handleNotificationClick = () => {
    setShowNotificationDropdown(!showNotificationDropdown);
  };

  const handleUserAvatarClick = () => {
    setShowUserDropdown(!showUserDropdown);
  };

  const handleUserProfileClick = () => {
    navigate('/user-profile');
  };

  const handleUserSettingsClick = () => {
    navigate('/settings');
  };

  const handleUserLogoutClick = () => {
    if (confirm('确定要退出登录吗？')) {
      navigate('/login');
    }
  };

  return (
    <div className={styles.pageWrapper}>
      {/* 顶部导航栏 */}
      <header id="top-nav" className="fixed top-0 left-0 right-0 bg-white border-b border-border-light h-16 z-50">
        <div className="flex items-center justify-between h-full px-6">
          {/* Logo和产品名称 */}
          <div id="logo-section" className="flex items-center space-x-3">
            <div className="w-8 h-8 bg-primary rounded-lg flex items-center justify-center">
              <i className="fas fa-utensils text-white text-sm"></i>
            </div>
            <h1 className="text-xl font-bold text-text-primary">食算</h1>
          </div>
          
          {/* 全局搜索框 */}
          <div id="global-search" className="flex-1 max-w-md mx-8">
            <div className="relative">
              <input 
                type="text" 
                id="search-input" 
                placeholder="搜索食物..." 
                value={searchInputValue}
                onChange={(e) => setSearchInputValue(e.target.value)}
                onKeyPress={handleSearchKeyPress}
                className="w-full pl-10 pr-4 py-2 border border-border-light rounded-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent"
              />
              <i className="fas fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-text-secondary"></i>
            </div>
          </div>
          
          {/* 右侧操作区 */}
          <div id="header-actions" className="flex items-center space-x-4">
            {/* 消息通知 */}
            <div id="notification-container" className="relative">
              <button 
                id="notification-btn" 
                className="relative p-2 text-text-secondary hover:text-primary"
                onClick={handleNotificationClick}
              >
                <i className="fas fa-bell text-lg"></i>
                <span className="absolute -top-1 -right-1 w-3 h-3 bg-danger rounded-full"></span>
              </button>
              <div className={`${styles.notificationDropdown} ${showNotificationDropdown ? styles.show : ''}`}>
                <div className={styles.dropdownItem}>
                  <div className="flex items-center space-x-3">
                    <i className="fas fa-check-circle text-secondary"></i>
                    <div>
                      <p className="text-sm font-medium">目标达成</p>
                      <p className="text-xs text-text-secondary">恭喜！今日卡路里摄入已达标</p>
                    </div>
                  </div>
                </div>
                <div className={styles.dropdownItem}>
                  <div className="flex items-center space-x-3">
                    <i className="fas fa-info-circle text-info"></i>
                    <div>
                      <p className="text-sm font-medium">营养提醒</p>
                      <p className="text-xs text-text-secondary">建议增加蛋白质摄入</p>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            {/* 用户头像和下拉菜单 */}
            <div id="user-menu-container" className="relative">
              <button 
                id="user-avatar-btn" 
                className="flex items-center space-x-2 p-1 rounded-lg hover:bg-gray-100"
                onClick={handleUserAvatarClick}
              >
                <img 
                  src="https://s.coze.cn/image/vhrkPO62yxY/" 
                  alt="用户头像" 
                  className="w-8 h-8 rounded-full" 
                  data-category="人物"
                />
                <span className="text-sm text-text-primary">张三</span>
                <i className="fas fa-chevron-down text-xs text-text-secondary"></i>
              </button>
              <div className={`${styles.userDropdown} ${showUserDropdown ? styles.show : ''}`}>
                <div className={styles.dropdownItem} onClick={handleUserProfileClick}>
                  <div className="flex items-center space-x-3">
                    <i className="fas fa-user text-text-secondary"></i>
                    <span className="text-sm">个人资料</span>
                  </div>
                </div>
                <div className={styles.dropdownItem} onClick={handleUserSettingsClick}>
                  <div className="flex items-center space-x-3">
                    <i className="fas fa-cog text-text-secondary"></i>
                    <span className="text-sm">设置</span>
                  </div>
                </div>
                <div className={styles.dropdownItem} onClick={handleUserLogoutClick}>
                  <div className="flex items-center space-x-3">
                    <i className="fas fa-sign-out-alt text-text-secondary"></i>
                    <span className="text-sm">退出登录</span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </header>

      {/* 左侧菜单 */}
      <aside id="sidebar" className={`fixed left-0 top-16 bottom-0 w-60 bg-white border-r border-border-light ${styles.sidebarTransition} z-40`}>
        <nav id="sidebar-nav" className="p-4">
          <ul className="space-y-2">
            <li>
              <Link to="/home" id="nav-home" className={`${styles.navItem} ${styles.navItemActive} flex items-center space-x-3 px-4 py-3 rounded-lg`}>
                <i className="fas fa-home text-lg"></i>
                <span className="font-medium">首页</span>
              </Link>
            </li>
            <li>
              <Link to="/food-search" id="nav-food-search" className={`${styles.navItem} flex items-center space-x-3 px-4 py-3 rounded-lg text-text-secondary`}>
                <i className="fas fa-search text-lg"></i>
                <span className="font-medium">食物搜索</span>
              </Link>
            </li>
            <li>
              <Link to="/record-list" id="nav-record-list" className={`${styles.navItem} flex items-center space-x-3 px-4 py-3 rounded-lg text-text-secondary`}>
                <i className="fas fa-list text-lg"></i>
                <span className="font-medium">饮食记录</span>
              </Link>
            </li>
            <li>
              <Link to="/history" id="nav-history" className={`${styles.navItem} flex items-center space-x-3 px-4 py-3 rounded-lg text-text-secondary`}>
                <i className="fas fa-history text-lg"></i>
                <span className="font-medium">历史记录</span>
              </Link>
            </li>
            <li>
              <Link to="/settings" id="nav-settings" className={`${styles.navItem} flex items-center space-x-3 px-4 py-3 rounded-lg text-text-secondary`}>
                <i className="fas fa-cog text-lg"></i>
                <span className="font-medium">设置</span>
              </Link>
            </li>
          </ul>
        </nav>
      </aside>

      {/* 主内容区 */}
      <main id="main-content" className="ml-60 mt-16 p-6 min-h-screen">
        {/* 页面头部 */}
        <div id="page-header" className="flex items-center justify-between mb-8">
          <div>
            <h2 className="text-2xl font-bold text-text-primary">欢迎回来，张三</h2>
            <nav id="breadcrumb" className="flex items-center space-x-2 text-sm text-text-secondary mt-1">
              <span>首页</span>
            </nav>
          </div>
          <button 
            id="quick-add-btn" 
            className="bg-primary text-white px-6 py-3 rounded-lg hover:bg-indigo-600 transition-colors flex items-center space-x-2"
            onClick={handleQuickAddClick}
          >
            <i className="fas fa-plus"></i>
            <span>快速添加食物</span>
          </button>
        </div>

        {/* 当日摄入总览区 */}
        <section id="daily-overview" className="bg-white rounded-2xl shadow-card p-6 mb-8">
          <h3 className="text-lg font-semibold text-text-primary mb-6">今日摄入总览</h3>
          <div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
            {/* 卡路里进度 */}
            <div id="calorie-progress" className="lg:col-span-2">
              <div className="flex items-center justify-between mb-4">
                <span className="text-text-secondary">卡路里</span>
                <span className="text-lg font-semibold text-text-primary">1,245 / 2,000 kcal</span>
              </div>
              <div className="w-full bg-gray-200 rounded-full h-3 mb-4">
                <div className={`${styles.progressBar} h-3 rounded-full`} style={{width: '62%'}}></div>
              </div>
              <div className="flex justify-between text-sm text-text-secondary">
                <span>已摄入: 1,245 kcal</span>
                <span>剩余: 755 kcal</span>
              </div>
            </div>
            
            {/* 营养成分 */}
            <div id="nutrition-overview" className="space-y-4">
              <div className="flex justify-between items-center">
                <span className="text-text-secondary">蛋白质</span>
                <span className="font-semibold text-text-primary">68g</span>
              </div>
              <div className="flex justify-between items-center">
                <span className="text-text-secondary">碳水化合物</span>
                <span className="font-semibold text-text-primary">156g</span>
              </div>
              <div className="flex justify-between items-center">
                <span className="text-text-secondary">脂肪</span>
                <span className="font-semibold text-text-primary">42g</span>
              </div>
            </div>
          </div>
        </section>

        {/* 今日饮食记录概览 */}
        <section id="today-records" className="bg-white rounded-2xl shadow-card p-6 mb-8">
          <div className="flex items-center justify-between mb-6">
            <h3 className="text-lg font-semibold text-text-primary">今日饮食记录</h3>
            <a 
              href="#" 
              id="view-all-records" 
              className="text-primary hover:text-indigo-600 text-sm font-medium"
              onClick={handleViewAllRecordsClick}
            >
              查看全部
            </a>
          </div>
          <div id="records-list" className="space-y-4">
            {/* 早餐 */}
            <div 
              className="record-item flex items-center justify-between p-4 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors cursor-pointer" 
              data-record-id="record-1"
              onClick={handleRecordItemClick}
            >
              <div className="flex items-center space-x-4">
                <img 
                  src="https://s.coze.cn/image/FLqsY01X1uM/" 
                  alt="燕麦粥" 
                  className="w-12 h-12 rounded-lg object-cover" 
                  data-category="食物"
                />
                <div>
                  <h4 className="font-medium text-text-primary">燕麦粥</h4>
                  <p className="text-sm text-text-secondary">早餐 · 08:30</p>
                </div>
              </div>
              <div className="text-right">
                <p className="font-semibold text-text-primary">320 kcal</p>
                <p className="text-sm text-text-secondary">150g</p>
              </div>
            </div>
            
            {/* 午餐 */}
            <div 
              className="record-item flex items-center justify-between p-4 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors cursor-pointer" 
              data-record-id="record-2"
              onClick={handleRecordItemClick}
            >
              <div className="flex items-center space-x-4">
                <img 
                  src="https://s.coze.cn/image/zLC_GZrD0_E/" 
                  alt="鸡胸肉沙拉" 
                  className="w-12 h-12 rounded-lg object-cover" 
                  data-category="食物"
                />
                <div>
                  <h4 className="font-medium text-text-primary">鸡胸肉沙拉</h4>
                  <p className="text-sm text-text-secondary">午餐 · 12:15</p>
                </div>
              </div>
              <div className="text-right">
                <p className="font-semibold text-text-primary">450 kcal</p>
                <p className="text-sm text-text-secondary">200g</p>
              </div>
            </div>
            
            {/* 下午茶 */}
            <div 
              className="record-item flex items-center justify-between p-4 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors cursor-pointer" 
              data-record-id="record-3"
              onClick={handleRecordItemClick}
            >
              <div className="flex items-center space-x-4">
                <img 
                  src="https://s.coze.cn/image/zdbWGnVKb1c/" 
                  alt="苹果" 
                  className="w-12 h-12 rounded-lg object-cover" 
                  data-category="食物"
                />
                <div>
                  <h4 className="font-medium text-text-primary">苹果</h4>
                  <p className="text-sm text-text-secondary">下午茶 · 15:30</p>
                </div>
              </div>
              <div className="text-right">
                <p className="font-semibold text-text-primary">85 kcal</p>
                <p className="text-sm text-text-secondary">1个</p>
              </div>
            </div>
          </div>
        </section>

        {/* 快速添加入口 */}
        <section id="quick-actions" className="grid grid-cols-1 md:grid-cols-3 gap-6">
          {/* 文字搜索 */}
          <div 
            id="quick-search-card" 
            className={`quick-action-card bg-white rounded-2xl shadow-card p-6 ${styles.cardHover} cursor-pointer`}
            onClick={handleQuickSearchClick}
          >
            <div className="flex items-center space-x-4 mb-4">
              <div className="w-12 h-12 bg-primary bg-opacity-10 rounded-lg flex items-center justify-center">
                <i className="fas fa-search text-primary text-xl"></i>
              </div>
              <div>
                <h4 className="font-semibold text-text-primary">文字搜索</h4>
                <p className="text-sm text-text-secondary">快速查找食物</p>
              </div>
            </div>
            <p className="text-text-secondary text-sm">输入食物名称，快速找到你想要的食物信息</p>
          </div>
          
          {/* 图片识别 */}
          <div 
            id="quick-camera-card" 
            className={`quick-action-card bg-white rounded-2xl shadow-card p-6 ${styles.cardHover} cursor-pointer`}
            onClick={handleQuickCameraClick}
          >
            <div className="flex items-center space-x-4 mb-4">
              <div className="w-12 h-12 bg-secondary bg-opacity-10 rounded-lg flex items-center justify-center">
                <i className="fas fa-camera text-secondary text-xl"></i>
              </div>
              <div>
                <h4 className="font-semibold text-text-primary">图片识别</h4>
                <p className="text-sm text-text-secondary">智能识别食物</p>
              </div>
            </div>
            <p className="text-text-secondary text-sm">拍照或上传图片，AI智能识别食物种类</p>
          </div>
          
          {/* 常见食物库 */}
          <div 
            id="quick-library-card" 
            className={`quick-action-card bg-white rounded-2xl shadow-card p-6 ${styles.cardHover} cursor-pointer`}
            onClick={handleQuickLibraryClick}
          >
            <div className="flex items-center space-x-4 mb-4">
              <div className="w-12 h-12 bg-tertiary bg-opacity-10 rounded-lg flex items-center justify-center">
                <i className="fas fa-archive text-tertiary text-xl"></i>
              </div>
              <div>
                <h4 className="font-semibold text-text-primary">常见食物库</h4>
                <p className="text-sm text-text-secondary">浏览分类食物</p>
              </div>
            </div>
            <p className="text-text-secondary text-sm">按分类浏览常见食物，快速选择添加</p>
          </div>
        </section>
      </main>
    </div>
  );
};

export default HomePage;

